<template>
  <div>
    <el-button type="primary" @click="showDialog = true">打开对话框</el-button>
    
    <el-dialog v-model="showDialog" title="简化表单验证" width="500px">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="1" :max="120" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'

const showDialog = ref(false)
const formRef = ref<FormInstance>()

const form = reactive({
  name: '',
  age: 18
})

const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 120, message: '年龄必须在1-120之间', trigger: 'blur' }
  ]
}

const submitForm = () => {
  // 关键：使用 Promise 方式验证
  formRef.value?.validate((valid, fields) => {
    if (valid) {
      ElMessage.success('验证通过！')
      console.log('表单数据:', form)
      showDialog.value = false
    } else {
      ElMessage.error('请检查表单填写')
      console.log('验证失败:', fields)
    }
  })
}
</script> 